import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView
  },
  {
    path: '/type',
    name: 'type',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/TypeView.vue')
  },
  {
    path: '/cart',
    name: 'cart',
    component: () => import('../views/CartView.vue'),
    meta: {
      auth: true
    }
  },
  {
    path: '/search',
    name: 'search',
    component: () => import('../views/SearchView.vue'),
    meta: {
      hidetabbar: true
    }
  },
  {
    path: '/person',
    name: 'person',
    component: () => import('../views/PersonView.vue'),
    meta: {
      auth: true
    }
  },
  {
    path: '/detail/:id',
    name: 'detail',
    component: () => import('../views/DetailView.vue'),
    meta: {
      hidetabbar: true
    }
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/LoginView.vue'),
    meta: {
      hidetabbar: true
    }
  },
  {
    path: '/sum',
    name: 'sum',
    component: () => import('../views/SumView.vue'),
    meta: {
      hidetabbar: true
    }
  },
  {
    path: '/area',
    name: 'area',
    component: () => import('../views/AreaView.vue'),
    meta: {
      hidetabbar: true
    }
  }
]

// 解决 从a到a  以及重定向错误
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject)
    return originalPush.call(this, location, onResolve, onReject);
  return originalPush.call(this, location).catch((err) => err);
};


const router = new VueRouter({
  routes
})

import store from "@/store"
// 全局路由守卫
// t跳转到 f当前路由 n下一步
router.beforeEach((t, f, n) => {
  if (t.meta.auth) {
    // 如果需要用户权限
    // 如果登陆过 直接去下一步
    if (store.getters.getUserInfo) {
      n();
    }
    // 如果未登录则去登录页面 并且拼接/next = t.path
    else {
      n({
        name: 'login',
        query: {
          next: t.path
        }
      })
    }
  }
  else {
    // 不需要用户权限直接去下一步
    n();
  }
})

export default router
